package com.runa.monitor.platinterface.netservice.handler;

import com.runa.monitor.platinterface.netservice.equipment.NetEqu;
import com.runa.protocol.dto.IInterData;
import com.runa.protocol.util.ByteUtil;
import com.runa.rccprotocol.dto.ConcentratorRequestData;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zhuj
 */
@ChannelHandler.Sharable
public class ProtocolEncoder extends MessageToByteEncoder<IInterData> {

    private static final Logger logger = LoggerFactory.getLogger(ProtocolEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, IInterData msg, ByteBuf out) {
        Object data = msg.getData();
        if (null != data) {
            out.writeBytes((byte[]) data);
        }
        if (msg instanceof ConcentratorRequestData) {
            logger.info("ToData:{}  Serial:{}  Encode:{}  Local:{}",ctx.channel().remoteAddress(), NetEqu.getSerial(ctx.channel().id().asLongText()), ByteUtil.byteToHexString((byte[]) msg.getData()), ctx.channel().localAddress());
        } else {
            logger.info("ToDtuReport:{}  Serial:{}  Encode:{}  Local:{}",ctx.channel().remoteAddress(), NetEqu.getSerial(ctx.channel().id().asLongText()), ByteUtil.byteToHexString((byte[]) msg.getData()), ctx.channel().localAddress());
        }
    }
}
